const express = require('express');
const axios = require('axios');
const path = require('node:path');
// const cheerio = require('cheerio')

const app = express();
// express on its own has no notion
// of a "file". The express.static()
// middleware checks for a file matching
// the `req.path` within the directory
// that you pass it. In this case "GET /js/app.js"
// will look for "./public/js/app.js".
// const join1 = path.join('..', 'public')
// const join2 = path.join(__dirname, '..', 'public')
// const resolve1 = path.resolve('..', 'public')
// const resolve2 = path.resolve(__dirname, '..', 'public')
// console.log('dir', __dirname)
// console.log('join1', join1)
// console.log('join2', join2)
// console.log('resolve1', resolve1)
// console.log('resolve2', resolve2)
// dir D:\myProject\node-demo\juejin
// join1 ..\public
// join2 D:\myProject\node-demo\public
// resolve1 D:\myProject\public
// resolve2 D:\myProject\node-demo\public
app.use(express.static(path.join(__dirname, '..', 'public')));
app.use('/node_modules', express.static(path.join(__dirname, '..', 'node_modules')));
// Register ejs as .html. If we did
// not call this, we would need to
// name our views foo.ejs instead
// of foo.html. The __express method
// is simply a function that engines
// use to hook into the Express view
// system by default, so if we want
// to change "foo.ejs" to "foo.html"
// we simply pass _any_ function, in this
// case `ejs.__express`.

app.engine('.html', require('ejs').__express);

// Optional since express defaults to CWD/views

app.set('views', path.join(__dirname, '..', 'views'));
// Without this you would need to
// supply the extension to res.render()
// ex: res.render('users.html').
app.set('view engine', 'html');

// if you wanted to "prefix" you may use
// the mounting feature of Connect, for example
// "GET /static/js/app.js" instead of "GET /js/app.js".
// The mount-path "/static" is simply removed before
// passing control to the express.static() middleware,
// thus it serves the file correctly by ignoring "/static"
// app.use('/static', express.static(path.join(__dirname, 'public')));

// if for some reason you want to serve files from
// several directories, you can use express.static()
// multiple times! Here we're passing "./public/css",
// this will allow "GET /style.css" instead of "GET /css/style.css":
// app.use(express.static(path.join(__dirname, 'public', 'css')));

app.get('/search', async (req, res) => {
  const keyword = req.query.keyword || '';
  // const sortBy = req.query.sortBy || 'viewCount'; // 默认按照阅读量排序
  // const page = parseInt(req.query.page) || 1;
  // const pageSize = 10;
  // sort_type: 0,默认;1,最新优先;2,最热优先
  // limit: 限制条数
  // search_type: 搜索时间类型: 0,时间不限;1,最近一天;2,最近一周;3,最近三个月;

  try {
    // const response = await axios.get(`https://juejin.cn/search?query=${encodeURIComponent(keyword)}&sort=${sortBy}&page=${page}`)
    const response = await axios.get(
      `https://api.juejin.cn/search_api/v1/search?aid=2608&uuid=7168314789041751567&spider=0&query=${encodeURIComponent(
        keyword
      )}&id_type=0&cursor=0&limit=5&search_type=0&sort_type=2&version=1`
    );
    console.log(
      'response-keyword',
      keyword,
      response?.data?.data?.[0]?.result_model?.article_info?.title ||
        response?.data?.data ||
        '数据出错'
    );
    // const $ = cheerio.load(response.data)
    // const articles = []

    // $('.content-box .info-box').each((index, element) => {
    //   const title = $(element).find('.title').text().trim()
    //   const link = $(element).find('.title').attr('href')
    //   const viewCount = parseInt($(element).find('.meta-list .iconfont-like').next().text().trim())
    //   const likeCount = parseInt($(element).find('.meta-list .iconfont-like').text().trim())
    //   const collectCount = parseInt($(element).find('.meta-list .iconfont-collection').text().trim())

    //   articles.push({
    //     title,
    //     link,
    //     viewCount,
    //     likeCount,
    //     collectCount,
    //   })
    // })

    // const startIndex = (page - 1) * pageSize
    // const endIndex = startIndex + pageSize
    // const paginatedArticles = articles.slice(startIndex, endIndex)

    // res.json(response?.data?.data || [])
    res.render('search', {
      data: response?.data?.data || [],
      title: 'EJS example',
      header: 'Some users'
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'An error occurred' });
  }
});
app.get('/juejinSearch', async (req, res) => {
  const keyword = req.query.keyword || '';
  // const sortBy = req.query.sortBy || 'viewCount'; // 默认按照阅读量排序
  // const page = parseInt(req.query.page) || 1;
  // const pageSize = 10;
  // sort_type: 0,默认;1,最新优先;2,最热优先
  // limit: 限制条数
  // search_type: 搜索时间类型: 0,时间不限;1,最近一天;2,最近一周;3,最近三个月;

  try {
    // const response = await axios.get(`https://juejin.cn/search?query=${encodeURIComponent(keyword)}&sort=${sortBy}&page=${page}`)
    const response = await axios.get(
      `https://api.juejin.cn/search_api/v1/search?aid=2608&uuid=7168314789041751567&spider=0&query=${encodeURIComponent(
        keyword
      )}&id_type=0&cursor=0&limit=5&search_type=0&sort_type=2&version=1`
    );
    console.log(
      'juejinSearch-keyword',
      keyword,
      response?.data?.data?.[0]?.result_model?.article_info?.title ||
        response?.data?.data ||
        '数据出错'
    );
    // const $ = cheerio.load(response.data)
    // const articles = []

    // $('.content-box .info-box').each((index, element) => {
    //   const title = $(element).find('.title').text().trim()
    //   const link = $(element).find('.title').attr('href')
    //   const viewCount = parseInt($(element).find('.meta-list .iconfont-like').next().text().trim())
    //   const likeCount = parseInt($(element).find('.meta-list .iconfont-like').text().trim())
    //   const collectCount = parseInt($(element).find('.meta-list .iconfont-collection').text().trim())

    //   articles.push({
    //     title,
    //     link,
    //     viewCount,
    //     likeCount,
    //     collectCount,
    //   })
    // })

    // const startIndex = (page - 1) * pageSize
    // const endIndex = startIndex + pageSize
    // const paginatedArticles = articles.slice(startIndex, endIndex)

    res.json({
      code: '200',
      data: response?.data?.data || [],
      msg: 'success'
    });
    // res.render('search', {
    //   data: response?.data?.data || [],
    //   title: 'EJS example',
    //   header: 'Some users',
    // })
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'An error occurred' });
  }
});
// Dummy users
var users = [
  { name: 'tobi', email: 'tobi@learnboost.com' },
  { name: 'loki', email: 'loki@learnboost.com' },
  { name: 'jane', email: 'jane@learnboost.com' }
];

app.get('/users', function (req, res) {
  res.render('users', {
    users: users,
    title: 'EJS example',
    header: 'Some users'
  });
});
app.get('/searchFetch', function (req, res) {
  res.render('searchFetch', {
    data: [],
    title: 'juejin search',
    header: 'searchFetch'
  });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
